<template>
  <div class="container">
    <lan-header :config="headerConfig"></lan-header>
    <lan-search-form
      size="small"
      :config="searchFormConfig"
      :formData="searchForm"
      @search="search"
    >
      <template #start="scope">
        <el-date-picker
          style="width:200px"
          class="data-input"
          size="small"
          v-model="scope.data.start"
          type="datetime"
          placeholder="选择查询开始日期时间"
        ></el-date-picker>至
      </template>
      <template #end="scope">
        <el-date-picker
          style="width:200px"
          size="small"
          v-model="scope.data.end"
          type="datetime"
          placeholder="选择查询开始日期时间"
        ></el-date-picker>
      </template>
    </lan-search-form>
    <lan-table
      size="small"
      :config="dataTable"
      :tableData="tableData"
      @selection-change="handleSelectionChange"
      @search="search"
    >
      <template #type="scope">
        <el-input v-model="scope.row.type"></el-input>
      </template>
    </lan-table>
  </div>

</template>

<script>
import lanTable from '../../../components/lanTable';
import lanHeader from '../../../components/lanHeader';
import lanSearchForm from '../../../components/lanSearchForm';
import moment from 'moment';
import { MomentFormat, SortType } from '../../../constants/common';
import { Message, MessageBox } from 'element-ui';
import { getDeviceActivityLogListApi, deleteDeviceActivityLogApi } from '../../../api/deviceActivityLog';
import { parseError } from '../../../utils';

export default {
  components: {
    lanSearchForm,
    lanTable,
    lanHeader
  },
  data() {
    return {
      headerConfig: {
        title: '设备活动日志',
        buttons: [
          {
            isShow: () => this.userGuardList.includes(this.guard.DeviceActivityLogManage),
            text: '删除所选',
            icon: 'el-icon-delete',
            type: 'danger',
            size: 'small',
            method: () => {
              this.deleteSelectedLog();
            }
          },
          {
            isShow: () => this.userGuardList.includes(this.guard.DeviceActivityLogManage),
            text: '清除日志',
            icon: 'el-icon-delete',
            type: 'danger',
            size: 'small',
            method: () => {
              this.deleteAllLog();
            }
          }
        ]
      },

      searchFormConfig: {
        inline: true,
        size: 'small',
        formList: [
          {
            name: 'deviceName',
            type: 'input',
            placeholder: '设备名称'
          },
          {
            name: 'serialNumber',
            type: 'input',
            placeholder: '设备序列号'
          },
          {
            name: 'keyword',
            type: 'input',
            placeholder: '关键字'
          },
          {
            name: 'start',
            type: 'slot'
          },
          {
            name: 'end',
            type: 'slot'
          }
        ]
      },
      tableData: [],
      searchForm: {
        currentPage: 1,
        pageSizes: [5, 10, 20, 50, 100],
        pageSize: 10,
        totalCount: 0,
        sortType: SortType.DESC,
        orderBy: 'createdAt',
        deviceName: '',
        serialNumber: null,
        keyword: '',
        start: new Date(new Date(new Date().toLocaleDateString()).getTime()),
        end: new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000)
      },
      selectedDeviceActivityLogIdList: [],
      btnLoading: false,
      dataTable: {
        pageSize: 10,
        totalCount: 0,
        currentPage: 1,
        pageSizes: [5, 10, 20, 50, 100],
        sort: {
          sortType: SortType.DESC,
          orderBy: 'createAt'
        },
        columnList: [
          {
            label: '',
            type: 'selection'
          },
          {
            name: 'deviceName',
            label: '设备名称',
            width: '150'
          },
          {
            name: 'serialNumber',
            label: '设备序列号',
            width: '180'
          },
          {
            name: 'message',
            label: '活动日志内容',
            width: '200'
          },
          {
            name: 'detail',
            label: '活动日志详情'
          },
          {
            name: 'createdAt',
            label: '创建时间',
            sortable: true,
            width: '180'
          }
        ]
      }
    };
  },
  created() {
    this.search();
  },
  methods: {
    sortHandler(data) {
      if (!data.prop || !data.order) return;
      this.sortType = data.order == 'ascending' ? SortType.ASC : SortType.DESC;
      this.search();
    },
    handleSelectionChange(value) {
      this.selectedDeviceActivityLogIdList = value.map(item => {
        return item.id;
      });
    },
    search() {
      this.btnLoading = true;
      getDeviceActivityLogListApi(
        this.searchForm.currentPage - 1,
        this.searchForm.pageSize,
        this.searchForm.sortType,
        this.searchForm.orderBy,
        this.searchForm.start,
        this.searchForm.end,
        this.searchForm.deviceName,
        this.searchForm.serialNumber,
        this.searchForm.keyword
      )
        .then(({ total_count, data }) => {
          this.searchForm.totalCount = total_count;
          this.tableData = data.map(log => {
            return {
              id: log.id,
              deviceName: log.device_name,
              serialNumber: log.serial_number,
              message: log.message,
              detail: log.detail,
              createdAt: moment(log.created_at).format(MomentFormat)
            };
          });
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.btnLoading = false));
    },
    detail(id) {
      let deviceActivityLogDetailRoute = this.$router.resolve('/device/activity/detail/' + id);
      window.open(deviceActivityLogDetailRoute.href, '_blank');
    },
    deleteAllLog() {
      MessageBox.confirm('确认删除全部设备活动日志吗？', '删除提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          deleteDeviceActivityLogApi()
            .then(res => Message.success(`成功删除${res.count}条用户活动日志`))
            .catch(error => Message.error(parseError(error)))
            .finally(() => this.search());
        })
        .catch(() => {});
    },
    deleteSelectedLog() {
      if (this.selectedDeviceActivityLogIdList.length == 0) return Message.warning('请选择要删除的活动日志内容');
      MessageBox.confirm(`确认删除${this.selectedDeviceActivityLogIdList.length}条设备活动日志吗？`, '删除提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          deleteDeviceActivityLogApi(this.selectedDeviceActivityLogIdList)
            .then(res => Message.success(`成功删除${res.count}条设备活动日志`))
            .catch(error => Message.error(parseError(error)))
            .finally(() => this.search());
        })
        .catch(() => {});
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  padding: 10px;
}
.data-input {
  margin-right: 10px;
}
</style>
